﻿using System;
using System.IO;
using System.Text;

namespace SimpleToDoList.Helper
{
    /// <summary>
    /// 记录本地日志
    /// </summary>
    public static class LocalLogHelper
    {
        private static readonly object _lock = new object();

        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="type">日志归类</param>
        /// <param name="logInfo">日志内容</param>
        public static void WriteMyLogs(string type, string logInfo)
        {
            try
            {
                lock (_lock)
                {
                    var logPath = AppDomain.CurrentDomain.BaseDirectory;
                    var dateNow = DateTime.Now;
                    var strLogFile = logPath + "logs\\" + DateTime.Now.Date.ToString("yyyy-MM-dd") + ".log";

                    //判断是否存在文件夹
                    if (!Directory.Exists(logPath + "logs\\"))
                        Directory.CreateDirectory(logPath + "logs\\");

                    //判断日志文件是否存在
                    var sw = File.Exists(strLogFile) ? File.AppendText(strLogFile) : File.CreateText(strLogFile);

                    try
                    {
                        var strLog = new StringBuilder();
                        strLog.Append(dateNow.ToString("yyyy-MM-dd HH:mm:ss").Trim())
                              .Append("==>")
                              .Append("\t\t")
                              .Append(type)
                              .Append("\t\t")
                              .Append(logInfo)
                              .Append("\t\t");
                        sw.Write(strLog + "\r\n");
                    }
                    catch (Exception ex)
                    {
                        // ignored
                        Console.WriteLine("Error" + ex.Message);
                    }
                    finally
                    {
                        sw.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                // ignored
                Console.WriteLine("Error" + ex.Message);
            }
        }

        /// <summary>
        /// 记录日志
        /// </summary>
        public static void WriteMyLogs(string type, string logInfo, string param2, string param3, string param4)
        {
            var sParam = $"LogInfo={logInfo}&param2={param2}&param3={param3}&param4={param4}";
            WriteMyLogs(type, sParam);
        }
    }
}